/**
 * 冒泡排序
 * 2018年 03月 12日 星期一
 *
 * @author fireway
 */
import java.util.Arrays;

public class BubbleSort {
    private long mLArray[];

    private int mSize;

    public BubbleSort(int initialCapacity) {
        mLArray = new long[initialCapacity];
        mSize = 0;
    }

    public void insert(long value) {
        mLArray[mSize++] = value;
    }

    public void display() {
        System.out.print("[");
        for (int i = 0; i < mSize; i++) {
            System.out.print(mLArray[i]);
            if (i != mSize -1) {
                System.out.print(", ");
            }
        }
        System.out.print("]\n");
    }

    public void bubbleSort() {
        for (int i = mSize - 1; i > 0; i--) {  // (N - 1)趟
            String order = String.format("%2s", (mSize - i));
            System.out.print("order" + order + " : ");

            for (int j = 0; j < i; j++) {
                if (mLArray[j] > mLArray[j + 1]) {
                    // 实际上，使用一个独立的swap()方法不一定好，因为方法
                    // 调用会增加一些额外的消耗。
                    long temp = mLArray[j + 1];
                    mLArray[j + 1] = mLArray[j];
                    mLArray[j] = temp;
                }
            }

            System.out.print(Arrays.toString(mLArray));
            System.out.println("");
        }
    }

    /**
     * 改进版
     */
    public void bubbleSort2() {
        boolean flag = false;

        for (int i = mSize - 1; i > 0; i--) {  // (N - 1)趟
            String order = String.format("%2s", (mSize - i));
            System.out.print("order" + order + " : ");
            flag = false;

            for (int j = 0; j < i; j++) {
                if (mLArray[j] > mLArray[j + 1]) {
                    long temp = mLArray[j + 1];
                    mLArray[j + 1] = mLArray[j];
                    mLArray[j] = temp;
                    flag = true;
                }
            }

            // 说明数组已经全部有序，退出循环
            if (!flag) {
                System.out.println("");
                break;
            }
            System.out.print(Arrays.toString(mLArray));
            System.out.println("");
        }
    }
}

